﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XMK.Utils;
using System.Text;
using System.IO;

namespace XMK.Tadong.ServiceWeb.Handlers
{
    /// <summary>
    /// upload 的摘要说明
    /// </summary>
    public class upload : IHttpHandler
    {
        private string fullFileName = string.Empty;
        private string orginalFileName = string.Empty;
        private string[] fullFileNames;
        private string[] orginalFileNames;
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                string fileType = context.Request["fileType"];
                if (String.IsNullOrEmpty(fileType))
                {
                    setResponse(JsonHelper.ToJson(new { status = 1, msg = "请设置上传文件类型！" }));
                }
                else
                {
                    if (UploadFile(fileType))
                    {
                        context.Response.Write(JsonHelper.ToJson(new { status = 0, msg = "文件上传成功。", realName = string.Join(";", orginalFileNames), fileName = string.Join(";", fullFileNames) }));
                    }
                    else
                    {
                        context.Response.Write(JsonHelper.ToJson(new { status = 1, msg = "文件上传出错，请联系管理员" }));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("[文件上传异常:" + DateTime.Now.ToString() + "][文件类型:" + context.Request["filetype"].ToString() + "][异常信息：" + ex.Message + "]");
                context.Response.Write(JsonHelper.ToJson(new { status = 1, msg = "文件上传出错，请联系管理员" }));
                context.Response.Flush();
                context.Response.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private bool UploadFile(string fileType)
        {
            int fileCount =  HttpContext.Current.Request.Files.Count;
            if (fileCount > 0)
            {
                orginalFileNames = new string[fileCount];
                fullFileNames = new string[fileCount];
                try
                {
                    for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                    {
                        Random random = new Random(DateTime.Now.Minute);
                        string physicalPath = HttpContext.Current.Server.MapPath("~/attach");

                        orginalFileName = HttpContext.Current.Request.Files[i].FileName;
                        orginalFileNames[i] = orginalFileName;

                        string filename = DateTime.Now.ToString("ddHHmmssffff") + "_" + random.Next(10000).ToString() + GetExtension(orginalFileName);
                        string middelName = DateTime.Now.ToString(@"yyyy\/M");
                        fullFileName = middelName + "/" + filename;// 保存到数据库
                        string _fullFileName = "/" + fileType + "/" + middelName + "/" + filename;//完整路径
                        string FolderName = "/" + fileType + "/" + middelName;//文件夹
                        fullFileNames[i] = fullFileName;
                        if (!Directory.Exists(physicalPath + FolderName))
                        {
                            Directory.CreateDirectory(physicalPath + FolderName);
                        }
                        HttpContext.Current.Request.Files[i].SaveAs(physicalPath + _fullFileName);
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog("[文件上传异常:" + DateTime.Now.ToString() + "][文件名称:" + fileType + "\\" + fullFileName + "][异常信息：" + ex.Message + "]");
                    return false;
                }

            }
            return false;
        }

        private string GetExtension(string filename)
        {
            FileInfo fileInfo = new FileInfo(filename);
            return fileInfo.Extension;
        }
        private void setResponse(string result)
        {
            byte[] bytes = Encoding.GetEncoding("gb2312").GetBytes(result);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = false;
            HttpContext.Current.Response.Charset = "gb2312";
            HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("gb2312");
            HttpContext.Current.Response.ContentType = "text/plain";
            HttpContext.Current.Response.AppendHeader("Content-Length", bytes.Length.ToString());
            HttpContext.Current.Response.Write(bytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Close();
        }
    }
}